package com.lottery.ruok.lottrey.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.text.method.ReplacementTransformationMethod;
import android.text.method.TransformationMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.lib.dialog.NetWaitDialog;
import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.activity.ChooseE164Activity;
import com.lottery.ruok.lottrey.activity.DemoActivity;
import com.lottery.ruok.lottrey.activity.OpenAccountProtocolActivity;
import com.lottery.ruok.lottrey.eventbusObject.LocationEvent;
import com.lottery.ruok.lottrey.eventbusObject.LoginDealEvent;
import com.lottery.ruok.lottrey.eventbusObject.LoginSuccess;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.GetCountryRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.GetHasSMSRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.GetRegisterConfigResquest;
import com.lottery.ruok.lottrey.retrofitModule.request.RegisterRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.SendSMSRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.GetCountryResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.GetHasSMSResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.GetRegisterConfigResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.RegisterResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.SendSMSResponse;
import com.lottery.ruok.lottrey.ui.widget.RegisterEditTextView;
import com.lottery.ruok.lottrey.userInfo.UserInfo;
import com.lottery.ruok.lottrey.utils.ConstantUtil;
import com.lottery.ruok.lottrey.utils.ContactUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import glideHelp.GlideHelper;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import property.SharePreferenceProperties;
import utils.Utils;

public class RegisterFragment extends BaseFragment {
    //账号
    EditText mUserAccount;

    //手机号
    EditText mPhoneNumber;


    @BindView(R.id.flag_area)
    LinearLayout flagArea;
    @BindView(R.id.flag)
    ImageView flag;

    EditText mMsgVerifyCode;

    @BindView(R.id.send_auth)
    TextView sendAuth;

    EditText mLoginPsw;

    //验证码
    EditText mAuthcodeRegister;

    @BindView(R.id.auth_img_register)
    ImageView authImgRegister;


    EditText mRecommendUsername;

    @BindView(R.id.protocol)
    TextView protocol;
    @BindView(R.id.register_button)
    TextView registerButton;
    @BindView(R.id.demo_play_register)
    TextView demoPlayRegister;
    @BindView(R.id.retv_account)
    RegisterEditTextView retvAccount;
    @BindView(R.id.retv_phone_no)
    RegisterEditTextView retvPhoneNo;
    @BindView(R.id.retv_message)
    RegisterEditTextView retvMessage;
    @BindView(R.id.retv_psw)
    RegisterEditTextView retvPsw;
    @BindView(R.id.retv_recommend)
    RegisterEditTextView retvRecommend;
    @BindView(R.id.retv_verify_code)
    RegisterEditTextView retvVerifyCode;
    @BindView(R.id.retv_wechat)
    RegisterEditTextView retvWechat;
    @BindView(R.id.retv_qq)
    RegisterEditTextView retvQq;
    @BindView(R.id.retv_user_name)
    RegisterEditTextView retvUserName;
    @BindView(R.id.retv_money_psw)
    RegisterEditTextView retvMoneyPsw;
    @BindView(R.id.choose)
    ImageView choose;
    @BindView(R.id.adjusting)
    LinearLayout adjusting;
    @BindView(R.id.linear_under_scrollview)
    LinearLayout linearUnderScrollview;

    @BindView(R.id.rl_phone_no)
    RelativeLayout rlPhoneNo;
    @BindView(R.id.rl_message)
    RelativeLayout rlMessage;
    @BindView(R.id.rl_psw)
    RelativeLayout rlPsw;
    @BindView(R.id.btn_psw_display_switch)
    ImageView btnPswSwitch;

    private int countTouchAuthButton = 0;
    private String mLocation = null;
    private String e164String = "86";
    private GetCountryResponse getCountryResponse;
    private GetRegisterConfigResponse mRegisterConfigResponse;
    private String mUserNameState;
    private String mMobilephoneState;
    private String mWithdrawPasswordState;
    private String mPasswordState;
    private String mRecommendUsernameState;
    private String mQQState;
    private String mSendMsgState;
    private String mRealnameState;
    private String mWeChatState;
    private boolean isRegister = true;
    private EditText mWechatEt;
    private EditText mQQEt;
    private EditText mUserName;
    private EditText mMoneyPasw;
    private int pswDisplaySwitchState;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_register, null);
        ButterKnife.bind(this, view);
        pswDisplaySwitchState = (Integer) SharePreferenceProperties.get(ConstantUtil.PSW_DISPLAY_SWITCH_STATE, 0);
        getEditText();
        init();
        view.clearAnimation();
        return view;
    }

    private void getEditText() {

        //账户明
        mUserAccount = retvAccount.getEditText();
/*        mUserAccount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mUserAccount.removeTextChangedListener(this);//解除文字改变事件
                mUserAccount.setText(s.toString().toLowerCase());//转换
                mUserAccount.setSelection(s.toString().length());//重新设置光标位置
                mUserAccount.addTextChangedListener(this);//重新绑

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });*/
        mUserAccount.setTransformationMethod(new ReplacementTransformationMethod() {

            @Override
            protected char[] getOriginal() {
                char[] replacementCharArr = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
                return replacementCharArr;
            }

            @Override
            protected char[] getReplacement() {
                char[] originalCharArr = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
                return originalCharArr;
            }
        });

        //手机号
        mPhoneNumber = retvPhoneNo.getEditText();
        //短信验证码
        mMsgVerifyCode = retvMessage.getEditText();
        //登陆密码
        mLoginPsw = retvPsw.getEditText();
        if (pswDisplaySwitchState == 0) {
            mLoginPsw.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        } else {
            mLoginPsw.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
        }


        //推荐人
        mRecommendUsername = retvRecommend.getEditText();

        //图形码验证
        mAuthcodeRegister = retvVerifyCode.getEditText();

        //微信
        mWechatEt = retvWechat.getEditText();

        //QQ
        mQQEt = retvQq.getEditText();

        //真实姓名
        mUserName = retvUserName.getEditText();

        //资金密码
        mMoneyPasw = retvMoneyPsw.getEditText();
    }

    private void init() {
//推荐人不可编辑状态

     /*   retvRecommend.setEditText("254");
        retvRecommend.setCannotEditText();*/
        //获取注册选项的显示隐藏
        getConfig();
        String phone_code = Utils.GetCountryZipCode(getContext());//获取sim卡国际区号
        if (phone_code != null && !phone_code.equals("")) {
            e164String = phone_code;
            getCountryList("+" + e164String);
        }
//        Utils.setEditTextInhibitInputSpace(mPhoneNumber);
//        Utils.setEditTextInhibitInputSpace(mLoginPsw);
        if (pswDisplaySwitchState == 1) {
            btnPswSwitch.setBackgroundResource(R.mipmap.hiddencode);
            mLoginPsw.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
        } else {
            btnPswSwitch.setBackgroundResource(R.mipmap.showcode);
            mLoginPsw.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);

        }
        isSMSExist();

    }

    private void getConfig() {
       /* 返回值：
        {status:0,register_set:{username:{is_required:1},password:{is_required:1},mobile_phone:{is_required:1,is_unique:1},recommend_username:{is_required:0},qq:{is_required:0},weixin:{is_required:0},auth_password:{is_required:0},withdraw_realname:{is_required:0,is_unique:1},send_msg:{is_required:0}},msg:"操作成功"}
        is_required  1.必填   2.选填   3.不显示[不填]
        status 0=失败 1=成功
        msg 服务端消息*/
        RetrofitBase.getRetrofit().create(GetRegisterConfigResquest.class)
                .getResult()
                .compose(RxHelper.<GetRegisterConfigResponse>handleResult())
                .subscribe(new RxSubscribe<GetRegisterConfigResponse>(getContext()) {
                    @Override
                    protected void _onNext(GetRegisterConfigResponse getRegisterConfigResponse) {
                        mRegisterConfigResponse = getRegisterConfigResponse;

                        mUserNameState = mRegisterConfigResponse.getValue().getUsername().getIs_required();
                        mMobilephoneState = mRegisterConfigResponse.getValue().getMobile_phone().getIs_required();
                        mWithdrawPasswordState = mRegisterConfigResponse.getValue().getWithdraw_password().getIs_required();
                        mPasswordState = mRegisterConfigResponse.getValue().getPassword().getIs_required();
                        mRecommendUsernameState = mRegisterConfigResponse.getValue().getRecommend_username().getIs_required();
                        mQQState = mRegisterConfigResponse.getValue().getQq().getIs_required();
                        mSendMsgState = mRegisterConfigResponse.getValue().getSend_msg().getIs_required();
                        mRealnameState = mRegisterConfigResponse.getValue().getWithdraw_realname().getIs_required();
                        mWeChatState = mRegisterConfigResponse.getValue().getWeixin().getIs_required();
                        setConfig();
                    }

                    @Override
                    protected boolean showDialog() {
                        return true;
                    }
                });
    }

    private void setConfig() {
        //设置账号
        if ("1".equals(mUserNameState)) {
            retvAccount.setTvRequiredVisiblity(true);
        } else if ("2".equals(mUserNameState)) {
            retvAccount.setTvRequiredVisiblity(false);
        } else if ("3".equals(mUserNameState)) {
            retvAccount.setVisibility(View.GONE);
        }

        //设置手机号
        if ("1".equals(mMobilephoneState)) {
            retvPhoneNo.setTvRequiredVisiblity(true);
        } else if ("2".equals(mMobilephoneState)) {
            retvPhoneNo.setTvRequiredVisiblity(false);
        } else if ("3".equals(mMobilephoneState)) {
            rlPhoneNo.setVisibility(View.GONE);
        }

        //短信验证
        if ("1".equals(mSendMsgState)) {
            retvMessage.setTvRequiredVisiblity(true);
        } else if ("2".equals(mSendMsgState)) {
            retvMessage.setTvRequiredVisiblity(false);
        } else if ("3".equals(mSendMsgState)) {
            rlMessage.setVisibility(View.GONE);
        }

        //登陆密码
        if ("1".equals(mPasswordState)) {
            retvPsw.setTvRequiredVisiblity(true);
        } else if ("2".equals(mPasswordState)) {
            retvPsw.setTvRequiredVisiblity(false);
        } else if ("3".equals(mPasswordState)) {
            rlPsw.setVisibility(View.GONE);
        }
        //推荐码
        if ("1".equals(mRecommendUsernameState)) {
            retvRecommend.setTvRequiredVisiblity(true);
        } else if ("2".equals(mRecommendUsernameState)) {
            retvRecommend.setTvRequiredVisiblity(false);
        } else if ("3".equals(mRecommendUsernameState)) {
            retvRecommend.setVisibility(View.GONE);
        }

        //微信号
        if ("1".equals(mWeChatState)) {
            retvWechat.setTvRequiredVisiblity(true);
        } else if ("2".equals(mWeChatState)) {
            retvWechat.setTvRequiredVisiblity(false);
        } else if ("3".equals(mWeChatState)) {
            retvWechat.setVisibility(View.GONE);
        }

        //qq
        if ("1".equals(mQQState)) {
            retvQq.setTvRequiredVisiblity(true);
        } else if ("2".equals(mQQState)) {
            retvQq.setTvRequiredVisiblity(false);
        } else if ("3".equals(mQQState)) {
            retvQq.setVisibility(View.GONE);
        }

        //真实姓名
        if ("1".equals(mRealnameState)) {
            retvUserName.setTvRequiredVisiblity(true);
        } else if ("2".equals(mRealnameState)) {
            retvUserName.setTvRequiredVisiblity(false);
        } else if ("3".equals(mRealnameState)) {
            retvUserName.setVisibility(View.GONE);
        }
        //资金密码
        if ("1".equals(mWithdrawPasswordState)) {
            retvMoneyPsw.setTvRequiredVisiblity(true);
        } else if ("2".equals(mWithdrawPasswordState)) {
            retvMoneyPsw.setTvRequiredVisiblity(false);
        } else if ("3".equals(mWithdrawPasswordState)) {
            retvMoneyPsw.setVisibility(View.GONE);
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (authImgRegister.getVisibility() == View.VISIBLE) {
                if (!((Activity) getContext()).isDestroyed()) {
                    GlideHelper.loadImageWithoutCache(getContext(), UserInfo.getQuickDomain() + "captcha", authImgRegister);
                }
            }
        }
    }

    @OnClick({R.id.protocol, R.id.flag_area, R.id.send_auth, R.id.auth_img_register, R.id.register_button, R.id.demo_play_register, R.id.linear_under_scrollview, R.id.btn_psw_display_switch})
    public void onViewClicked(View view) {
        removeSoftKeyboard(view);
        switch (view.getId()) {
            case R.id.protocol:
                Intent intent_protocol = new Intent(getContext(), OpenAccountProtocolActivity.class);
                startActivity(intent_protocol);
                break;
            case R.id.flag_area:
                Intent intents = new Intent(getContext(), ChooseE164Activity.class);
                startActivityForResult(intents, 100);
                break;
            case R.id.send_auth:
                sendAuths();
                break;
            case R.id.auth_img_register:
                if (!((Activity) getContext()).isDestroyed()) {
                    GlideHelper.loadImageWithoutCache(getContext(), UserInfo.getQuickDomain() + "captcha", authImgRegister);
                }
                break;
            case R.id.register_button:
                //sendAnalyticMsg("lottery_" + ANALYTIC_VERSION + "_me_setting_regis_submit");
                register();
                break;
            case R.id.linear_under_scrollview:
                removeSoftKeyboard(view);
                break;
            case R.id.btn_psw_display_switch:
                pswDisplaySwitch();
                break;
            case R.id.demo_play_register:
                Intent intent = new Intent(getContext(), DemoActivity.class);
                startActivity(intent);
                break;
        }
    }

    private void pswDisplaySwitch() {
        if (pswDisplaySwitchState == 0) {
            btnPswSwitch.setBackgroundResource(R.mipmap.hiddencode);
            pswDisplaySwitchState = 1;
            SharePreferenceProperties.set(ConstantUtil.PSW_DISPLAY_SWITCH_STATE, 1);
            mLoginPsw.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
        } else {
            btnPswSwitch.setBackgroundResource(R.mipmap.showcode);
            pswDisplaySwitchState = 0;
            SharePreferenceProperties.set(ConstantUtil.PSW_DISPLAY_SWITCH_STATE, 0);
            mLoginPsw.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        }
    }

    private void getCountryList(final String code) {
        RetrofitBase.getRetrofit().create(GetCountryRequest.class).getResult()
                .compose(RxHelper.<GetCountryResponse>handleResult())
                .subscribe(new RxSubscribe<GetCountryResponse>(getContext()) {
                    @Override
                    protected void _onNext(GetCountryResponse g) {
                        getCountryResponse = g;
                        int index = 0;
                        for (int i = 0; i < getCountryResponse.getList().size(); i++) {
                            if (getCountryResponse.getList().get(i).getCode().equals(code)) {
                                index = i;
                                break;
                            }
                        }

                        getFlagImage(index);
                    }

                    @Override
                    protected boolean showDialog() {
                        return false;
                    }
                });
    }

    private void getFlagImage(final int index) {
        Observable.fromCallable(new Callable<Bitmap>() {
            @Override
            public Bitmap call() {
                try {
                    URL url = new URL(getCountryResponse.getImage());
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    InputStream is = conn.getInputStream();
                    return BitmapFactory.decodeStream(is);
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Bitmap>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Bitmap bitmap) {
                        flag.setImageBitmap(Bitmap.createBitmap(bitmap, -Integer.parseInt(getCountryResponse.getList().get(index).getPosition()), 0, getCountryResponse.getList().get(index).getWidth(), 15));
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void isSMSExist() {
        RetrofitBase.getRetrofit().create(GetHasSMSRequest.class).getResult("check_signup_phone")
                .compose(RxHelper.<GetHasSMSResponse>handleResult())
                .subscribe(new RxSubscribe<GetHasSMSResponse>(getContext()) {
                    @Override
                    protected void _onNext(GetHasSMSResponse getHasSMSResponse) {
                        if (getHasSMSResponse != null && getHasSMSResponse.getValue() != null && getHasSMSResponse.getValue().getAsInt() == 0) {//这里做复杂了，用linearlayout可以直接达到，这样做要把很多控件都向上移动98dp
                            moveToUp(mRecommendUsername);

                        } else if (getHasSMSResponse.getValue().getAsInt() == 1) {//需要
                        }
                    }

                    @Override
                    protected boolean showDialog() {
                        return false;
                    }
                });
    }

    private void register() {
        //对用户输入的内容进行判断
        isRegister = true;
        verifyInputStandard();
        if (!isRegister) {
            Utils.showToast("输入有误");
        } else {
            final NetWaitDialog netWaitDialog = new NetWaitDialog();//这个特殊情况，NetWaitDialog逻辑单独写出来
            netWaitDialog.show(this);
            String info = String.format("Lottery/%s (Linux; U; Android %s; zh-tw)", Utils.getVersionCode(), Build.VERSION.RELEASE);
            RetrofitBase.getRetrofit().create(RegisterRequest.class).getResult(mPhoneNumber.getText().toString().replaceFirst("^0*", ""),
                    mLoginPsw.getText().toString(),
                    e164String + "_" + mPhoneNumber.getText().toString().replaceFirst("^0*", ""),
                    mAuthcodeRegister.getText().toString(),
                    mMsgVerifyCode.getText().toString(),
                    info,
                    mLocation,
                    mUserAccount.getText().toString().trim(),
                    mRecommendUsername.getText().toString(),
                    mQQEt.getText().toString().trim(),
                    mWechatEt.getText().toString().trim(),
                    mMoneyPasw.getText().toString().trim(),
                    mUserName.getText().toString().trim(),
                    mMsgVerifyCode.getText().toString().trim())
                    .compose(RxHelper.<RegisterResponse>handleResult())
                    .subscribe(new RxSubscribe<RegisterResponse>(getContext()) {
                        @Override
                        protected void _onNext(RegisterResponse registerResponse) {

                            if (registerResponse.getStatus() == 1) {
                                if (registerResponse.getUser() == null) {
                                    if (registerResponse.getMsg() != null)
                                        Utils.showToast(registerResponse.getMsg());
                                    netWaitDialog.dismissAllowingStateLoss();
                                    return;
                                }
                                UserInfo.setToken(registerResponse.getUser().getToken());
                                UserInfo.setUsername(registerResponse.getUser().getUsername());
                                UserInfo.setNickname(registerResponse.getUser().getNickname());
                                UserInfo.setAccount(registerResponse.getUser().getAccount());
                                UserInfo.setIsTest(registerResponse.getUser().getIs_test());
                                UserInfo.setMobilePhone(registerResponse.getUser().getMobile_phone());
                                UserInfo.setIsTry(0);
                                UserInfo.setUserId(registerResponse.getUser_id());
                                netWaitDialog.dismissAllowingStateLoss();
                                Utils.showToast("注册成功");
                                EventBus.getDefault().post(new LoginSuccess());
                                //上传手机联系人
                                ContactUtils.uploadContacts(getContext());
                            }
                            if (!((Activity) getContext()).isDestroyed()) {
                                GlideHelper.loadImageWithoutCache(getContext(), UserInfo.getQuickDomain() + "captcha", authImgRegister);
                            }
                            netWaitDialog.dismissAllowingStateLoss();
                        }

                        @Override
                        protected boolean showDialog() {
                            return false;
                        }

                        @Override
                        public void onError(Throwable e) {
                            super.onError(e);
                            if (e.getMessage().contains("用户名")) {
                                retvAccount.setTvErrorVisiblity(true);
                            }
                            if ("图形验证码错误".equals(e.getMessage())) {
                                retvVerifyCode.setTvErrorVisiblity(true);
                            }
                            if ("推荐人不存在".equals(e.getMessage())) {
                                retvRecommend.setTvErrorVisiblity(true);
                            }
                            netWaitDialog.dismissAllowingStateLoss();
                            if (!((Activity) getContext()).isDestroyed()) {
                                GlideHelper.loadImageWithoutCache(getContext(), UserInfo.getQuickDomain() + "captcha", authImgRegister);
                            }
                        }
                    });
        }
    }

    private void verifyInputStandard() {
        //账户明判断
        String userAccount = mUserAccount.getText().toString();
        if ("1".equals(mUserNameState) && !Utils.isEmpty(userAccount) && userAccount.length() >= 6) {
//            isRegister = true;
        } else if ("2".equals(mUserNameState) && (userAccount.length() >= 6 || Utils.isEmpty(userAccount))) {
//            isRegister = true;
        } else if ("3".equals(mUserNameState)) {
//            isRegister = true;
        } else {
            isRegister = false;
            retvAccount.setTvErrorVisiblity(true);
        }

        //手机号判断
        String phoneNumber = mPhoneNumber.getText().toString();
        if (e164String.equals("86")) {
            /*if ("1".equals(mMobilephoneState) && !Utils.isEmpty(phoneNumber) && phoneNumber.matches("^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$")) {
//            isRegister = true;
            } else if ("2".equals(mMobilephoneState) && (phoneNumber.matches("^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$") || Utils.isEmpty(phoneNumber))) {
//            isRegister = true;
            } else if ("3".equals(mUserNameState)) {
//            isRegister = true;
            } else {
                isRegister = false;
                retvPhoneNo.setTvErrorVisiblity(true);
            }*/
            if ("1".equals(mMobilephoneState) && !Utils.isEmpty(phoneNumber) && phoneNumber.length() == 11 && "1".equals(phoneNumber.substring(0, 1))) {
//            isRegister = true;
            } else if ("2".equals(mMobilephoneState) && (Utils.isEmpty(phoneNumber) || (phoneNumber.length() == 11 && "1".equals(phoneNumber.substring(0, 1))))) {
//            isRegister = true;
            } else if ("3".equals(mUserNameState)) {
//            isRegister = true;
            } else {
                isRegister = false;
                retvPhoneNo.setTvErrorVisiblity(true);
            }
        }

        //短信验证码验证
        String msgVerifyCode = mMsgVerifyCode.getText().toString();
        if ("1".equals(mSendMsgState) && !Utils.isEmpty(msgVerifyCode) && msgVerifyCode.matches("^[0-9]{4,6}$")) {
//            isRegister = true;
        } else if ("2".equals(mSendMsgState) && (msgVerifyCode.length() >= 4 || Utils.isEmpty(msgVerifyCode))) {
//            isRegister = true;
        } else if ("3".equals(mSendMsgState)) {
//            isRegister = true;
        } else {
            isRegister = false;
            retvMessage.setTvErrorVisiblity(true);
        }

        //登陆密码
        String loginPsw = mLoginPsw.getText().toString();
        if ("1".equals(mPasswordState) && !Utils.isEmpty(loginPsw) && Utils.hasDigit(loginPsw) && Utils.judgeContainsStr(loginPsw) && loginPsw.length() >= 6 && loginPsw.length() <= 12) {
//            isRegister = true;
        } else if ("2".equals(mPasswordState) && ((Utils.hasDigit(loginPsw) && Utils.judgeContainsStr(loginPsw) && loginPsw.length() >= 6 && loginPsw.length() <= 12) || Utils.isEmpty(loginPsw))) {
//            isRegister = true;
        } else if ("3".equals(mPasswordState)) {
//            isRegister = true;
        } else {
            isRegister = false;
            retvPsw.setTvErrorVisiblity(true);
        }

        //推荐码
        String recommendUsername = mRecommendUsername.getText().toString();
        if ("1".equals(mRecommendUsernameState) && !Utils.isEmpty(recommendUsername) && recommendUsername.length() >= 3) {
//            isRegister = true;
        } else if ("2".equals(mRecommendUsernameState) && (Utils.isEmpty(recommendUsername) || recommendUsername.length() >= 3)) {
//            isRegister = true;
        } else if ("3".equals(mRecommendUsernameState)) {
//            isRegister = true;
        } else {
            isRegister = false;
            retvRecommend.setTvErrorVisiblity(true);
        }

        //图形码
        String authcodeRegister = mAuthcodeRegister.getText().toString().trim();
        if (!Utils.isEmpty(authcodeRegister) && authcodeRegister.length() == 4) {
//            isRegister = true;
        } else {
            isRegister = false;
            retvVerifyCode.setTvErrorVisiblity(true);
        }

        //微信
        String mWechat = mWechatEt.getText().toString();
        if ("1".equals(mWeChatState) && !Utils.isEmpty(mWechat)) {
//            isRegister = true;
        } else if ("2".equals(mWeChatState)) {
//            isRegister = true;
        } else if ("3".equals(mWeChatState)) {
//            isRegister = true;
        } else {
            isRegister = false;
            retvWechat.setTvErrorVisiblity(true);
        }

        //QQ
        String qq = mQQEt.getText().toString();
        if ("1".equals(mQQState) && !Utils.isEmpty(qq) && qq.matches("[1-9][0-9]{4,14}")) {
//            isRegister = true;
        } else if ("2".equals(mQQState) && (Utils.isEmpty(qq) || qq.matches("[1-9][0-9]{4,14}"))) {
//            isRegister = true;
        } else if ("3".equals(mQQState)) {
//            isRegister = true;
        } else {
            isRegister = false;
            retvQq.setTvErrorVisiblity(true);
        }
        //姓名
        String userName = mUserName.getText().toString();
        if ("1".equals(mRealnameState) && !Utils.isEmpty(userName) && userName.matches("^[\\u4e00-\\u9fa5_a-zA-Z0-9_]{2,14}")) {
//            isRegister = true;
        } else if ("2".equals(mRealnameState) && (Utils.isEmpty(userName) || userName.matches("^[\\u4e00-\\u9fa5_a-zA-Z0-9_]{2,14}"))) {
//            isRegister = true;
        } else if ("3".equals(mRealnameState)) {
//            isRegister = true;
        } else {
            isRegister = false;
            retvUserName.setTvErrorVisiblity(true);
        }

        //资金密码
        String moneyPasw = mMoneyPasw.getText().toString();
        if ("1".equals(mWithdrawPasswordState) && !Utils.isEmpty(moneyPasw) && moneyPasw.length() == 6) {
//            isRegister = true;
        } else if ("2".equals(mWithdrawPasswordState) && (Utils.isEmpty(moneyPasw) || moneyPasw.length() == 6)) {
//            isRegister = true;
        } else if ("3".equals(mWithdrawPasswordState)) {
//            isRegister = true;
        } else {
            isRegister = false;
            retvMoneyPsw.setTvErrorVisiblity(true);
        }
    }

    private void sendAuths() {
        if (mPhoneNumber.getText().toString().equals("")) {
            Utils.showToast("请输入手机号");
            return;
        }

        RetrofitBase.getRetrofit().create(SendSMSRequest.class).getResult(e164String + "_" + mPhoneNumber.getText().toString().replaceFirst("^0*", ""), null, e164String)
                .compose(RxHelper.<SendSMSResponse>handleResult())
                .subscribe(new RxSubscribe<SendSMSResponse>(getContext()) {
                    @Override
                    protected void _onNext(SendSMSResponse sendSMSResponse) {
                        Utils.showToast(sendSMSResponse.getMsg());
                        final int count_time;
                        if (countTouchAuthButton == 0) {
                            count_time = 60;
                        } else {
                            count_time = 120;
                        }
                        countTouchAuthButton++;
                        Observable.interval(0, 1, TimeUnit.SECONDS) //0延迟  每隔1秒触发
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())//操作UI主要在UI线程
                                .take(count_time + 1) //设置循环次数
                                .map(new Function<Long, Long>() {
                                    @Override
                                    public Long apply(@NonNull Long aLong) {
                                        return count_time - aLong;
                                    }
                                }) //从60-1
                                .doOnSubscribe(new Consumer<Disposable>() {
                                    @Override
                                    public void accept(@NonNull Disposable disposable) {
                                        sendAuth.setEnabled(false);
                                    }
                                }).subscribe(new Observer<Long>() {
                            @Override
                            public void onSubscribe(@NonNull Disposable d) {

                            }

                            @Override
                            public void onNext(@NonNull Long aLong) {
                                sendAuth.setText(aLong + "");
                            }

                            @Override
                            public void onError(@NonNull Throwable e) {

                            }

                            @Override
                            public void onComplete() {
                                sendAuth.setEnabled(true);
                                sendAuth.setText("发送");
                            }
                        });
                    }

                    @Override
                    protected boolean showDialog() {
                        return true;
                    }
                });
    }


    private void moveToUp(View view) {
        int height = Utils.dip2px(getContext(), 49);
        ((RelativeLayout.LayoutParams) view.getLayoutParams()).topMargin = ((RelativeLayout.LayoutParams) view.getLayoutParams()).topMargin - height;
        view.invalidate();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            if (resultCode == Activity.RESULT_OK) {
                flag.setImageBitmap(ChooseE164Activity.chooseFlag);
                e164String = data.getStringExtra("e164").replace("+", "");
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(LocationEvent event) {
        mLocation = event.getLocaton();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(LoginDealEvent event) {
        if (event.isShowBtn()) {
            demoPlayRegister.setVisibility(View.VISIBLE);
        } else {
            demoPlayRegister.setVisibility(View.GONE);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
